<template>
  <teleport to="#message">
    <div class="alert message-info fixed-top w-50 mx-auto d-flex justify-content-between mt-2" :class="classObject"
      v-if="isVisible">
      <span>{{ message
      }}<span v-if="timeout">,{{ timer }}秒后{{ navigationMessage }}</span></span>
      <button type="button" class="btn-close" aria-label="Close" @click="hide"></button>
    </div>
  </teleport>
</template>

<script lang="ts">
import { defineComponent, PropType, ref, onMounted, computed } from "vue";
import useDOMCreate from "../hooks/useDOMCreate";
export type MessageType = "success" | "error" | "default";
export default defineComponent({
  props: {
    message: String,
    navigationMessage: String,
    timeout: Number,
    type: {
      type: String as PropType<MessageType>,
      default: "default"
    }
  },
  emits: ["close-message"],
  setup(props, context) {
    useDOMCreate("message");
    const isVisible = ref(true);
    const classObject = {
      "alert-success": props.type === "success",
      "alert-danger": props.type === "error",
      "alert-primary": props.type === "default"
    };
    const hide = () => {
      isVisible.value = false;
      context.emit("close-message", true);
    };
    // 定时器
    let timer = ref(0);
    if (props.timeout) {
      timer = ref(props.timeout / 1000);
      const countDown = setInterval(() => {
        if (timer.value) {
          timer.value--;
        }
        if (timer.value === 0) {
          clearInterval(countDown);
        }
      }, 1000);
    }
    return {
      classObject,
      isVisible,
      hide,
      timer
    };
  }
});
</script>
